<?php

namespace app\controller\api;

use app\BaseController;
use app\constant\CommonConstant;
use app\constant\ModelConstant;
use app\event\PushOrderToShopify;
use app\helpers\FormatHelper;
use app\helpers\UtilHelper;
use app\model\Notify;
use app\model\Orders;
use app\service\payment\PaymentFactory;
use app\trait\ShopifyTrait;
use Carbon\Carbon;
use think\facade\Event;
use think\helper\Arr;
use think\Request;

/**
 * @desc 加购
 */
class UpsellController extends BaseController
{
    use ShopifyTrait;
    public function upsell(Request $request,Orders $order)
    {
        Notify::saveParams($order->id,['params'=>$request->all()],Notify::TYPE_REPURCHASE);
        $upsell = null;
        try{
            $is_continue = $request->param('is_continue',0);
            if(!$is_continue) throw new \Exception("customer upsell not continue");
            $items = $request->post('line_items', []);
            if (empty($items)) throw new \Exception("line items required");
            $purchaser_status = $request->param('purchaser_status',1);//3ds加购失败,完成订单
            if (!$purchaser_status) throw new \Exception("3ds pay fail");
            if($order->order_status != Orders::ORDER_STATUS_COMPLETED) throw new \Exception("first order not pay success");
            if($order->is_completed) throw new \Exception("order is completed");
            $isExistsPurchase = $order->purchases()->where('order_status',Orders::ORDER_STATUS_COMPLETED)->find();
            if($isExistsPurchase) throw new \Exception("order has repurchase");
            $purchaseData = $this->getPurchaseData($order);
            $products = $this->getPurchaseItems($request);
            $purchaseData['pid'] = $order->id;
            $purchaseData['subtotal_present'] = $products['purchase_price'];
            $purchaseData['total_present'] = $products['purchase_price'];
            $upsell = Orders::create($purchaseData);
            $addresses = $order->addresses()->hidden(['order_id','id'])->select()->toArray();
            $upsell->items()->saveAll($products['line_items']);//保存商品
            $upsell->addresses()->saveAll($addresses);//保存地址
            $gateWay = PaymentFactory::factory($order->pay_method);
            $result = $gateWay->upsell($upsell,$request);
            return $this->success(['order_id'=>$upsell->id,'pay_result'=>$result,'target_url'=>Arr::get($result,'target_url')]);
        }catch (\Exception $e){
            if($upsell){
                Orders::saveExceptionMessage($upsell,$e->getMessage());
            }else{
                Orders::saveExceptionMessage($order,$e->getMessage());
            }
            if(!$order->is_completed);Orders::pushShopifyOrder($order->id);//队列运行
            $host = domain($order->shop->website);
            $target_url = FormatHelper::getLoadingUrl($host,$order->checkout_id,['order_id'=>$order->id,'cid'=>$request->header('x-opc-client-id')]);
            return $this->success(['target_url'=>$target_url]);

        }
    }



    protected function getPurchaseItems(Request $request)
    {
        $items = $request->post('line_items', []);
        $line_items = [];
        $purchasePrice = '0.00';
        $discount = config('payment.discount.value');//折扣
        $product_title = $request->post('product_title', 0);//标题
        foreach ($items as $line) {
            if(in_array($line['title'],CommonConstant::SHIPPING_PROTECTION_FEE)) continue;
            $price = Arr::get($line,'price','0.00');
            $quantity = Arr::get($line,'quantity', 1);
            $discountPrice = bcmul((string)$price,$discount,2);
            $subTotal = bcmul($discountPrice,(string)$quantity,2);
            $purchasePrice = bcadd($purchasePrice,$subTotal,2);
            $variant_id = Arr::get($line,'id',0);
            $line_items[] = [
                'product_id' => Arr::get($line,'product_id'),
                'sku' => $line['sku'] ?: $variant_id,
                'title' => ['title' => $product_title],
                'price' => $discountPrice,
                'variant_id' => $variant_id,
                'variant_title' => json_encode(['title' => Arr::get($line,'title','')]),
                'quantity' => $quantity,
                'origin_price'=>$price,
                'properties'=>[],
                'options_with_values'=>[],
                'image'=>Arr::get($line,'image','')
            ];
        }
        return [
            'line_items'=>$line_items,
            'purchase_price'=>$purchasePrice
        ];
    }

    public function getPurchaseData(Orders $order):array
    {
        $data = $order->getDatas();
        Arr::forget($data,['id','utc_at','cn_at','us_at']);
        $data['pay_id'] = $order->pay_id;
        $data['pay_method'] = $order->pay_method;
        $data['is_completed'] = ModelConstant::STATUS_OFF;
        $data['order_status'] = ModelConstant::STATUS_OFF;
        $data['order_type'] = Orders::ORDER_DRAFT;
        $data['present_currency'] = $order->present_currency;
        $data['shop_currency'] = $order->shop_currency;
        $data['draft_id'] = $order->draft_id;
        $data['shopify_order_id'] = '';
        $data['last_order_name'] = '';
        $data['name'] = $order->name;
        $data['order_no'] = '';
        $data['trade_no'] = '';
        $data['tongtu_code'] = '';
        $data['shipping_name'] = '';
        $data['discount_codes'] = [];
        $data['created_at'] = Carbon::now()->subHours(16)->toDateTimeString();
        $data['is_repurchase'] = ModelConstant::STATUS_ON;
        $data['shop_id'] = $order->shop_id;
        $data['subtotal_present'] = '0.00';
        $data['subtotal_shop'] = '0.00';
        $data['discount_present'] = '0.00';
        $data['discount_shop'] = '0.00';
        $data['total_present'] = '0.00';
        $data['total_shop'] = '0.00';
        $data['shipping_price_present'] = '0.00';
        $data['shipping_price_shop'] = '0.00';
        $data['shipping_protection'] = '0.00';
        $data['tax_shop'] = '0.00';
        $data['tax_present'] = '0.00';
        $data['actual_money'] = '0.00';
        $data['track_num'] = '';
        $data['is_import'] = ModelConstant::STATUS_OFF;
        $data['is_paypal_kj'] = ModelConstant::STATUS_OFF;
        $data['paypal_method'] = ModelConstant::STATUS_OFF;
        return $data;
    }
}